/**
 * class: Launcher
 * @author charmgil
 * CS2510 Project 3
 */

import java.util.*;
import core.*;
import common.*;
import simulator.*;

public class Launcher{
	public static void main( String[] args ){ 
		ArrayList<Thread> nodes = new ArrayList<Thread>();
		
		// proc
		Router network = new Router();
		network.start();
		
		for( int i = 0; i < Conf.NUMBER_OF_NODES; i++ ){
			nodes.add( new Node( network ) );
			for( int j = 0; j < 5000000; j++ );		// spinlock for thread init
			nodes.get( i ).start();
		}
		
		
		// simulator routine
		boolean simulate = true;
		
		if( simulate ){
			
			final int N_REQUEST = 1;
			
			
			// add analyzer
			Analyzer dr_watson = new Analyzer();
			network.add_analyzer( dr_watson );
			dr_watson.start();
			
			// inject requests
			for( int i = 0; i < N_REQUEST; i++ ){
				Resource r = new Resource( "lena_std.jpg" );
				java.util.ArrayList<Integer> subtasks = new java.util.ArrayList<Integer>();
				
				int n_subtasks = ( int )( Math.random() * 3 ) + 1;
				while( n_subtasks-- > 0 ){
					switch( ( int )( Math.random() * 3 ) ){
						case 0:
							subtasks.add( filter.FilterModuleList.GBLUR );
							break;
						case 1:
							subtasks.add( filter.FilterModuleList.BLUR );
							break;
						case 2:
							subtasks.add( filter.FilterModuleList.GRAYSCALE );
							break;
						case 3:
							subtasks.add( filter.FilterModuleList.BINARIZE );
							break;
						default:
							subtasks.add( filter.FilterModuleList.BLUR );
					}
				}
				Worklet request = new Worklet( r, subtasks, Def.SIMULATOR, Def.ROUTER_IP );
				
				// receiver
				int pid = ( int )( Math.random() * ( Conf.NUMBER_OF_NODES - 1 ) ) + 1;
				long ip = network.ip_lookup( pid );
				
				// msg
				Message msg = new Message( Def.REQUEST, pid, ip, Def.SIMULATOR, Def.ROUTER_IP,
						System.currentTimeMillis(), null, request );

				// send the msg (1-to-1)
				network.send( msg );
				
				System.out.println( "-simulator: a random request(" + request.get_wcet() + "/" + request.get_period() + ")[" + subtasks.size() + "] is sent to " + pid + ":" + Utils.ipToString( ip ) );
			}
		}
	}//end-of-main()
}//end-of-class


